package com.mxx.qh.dialog;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.makeramen.roundedimageview.RoundedImageView;
import com.mxx.qh.R;
import com.mxx.qh.SPUtils;
import com.mxx.qh.activity.MainActivity;
import com.mxx.qh.config.ConstantsConfig;
import com.mxx.qh.config.NetUrlConfig;
import com.mxx.qh.network.RequestEnum;
import com.mxx.qh.network.RetrofitHelper;
import com.mxx.qh.network.StringObserver;
import com.mxx.qh.response.AuthorizeInfo;
import com.mxx.qh.response.BaseResponse;
import com.mxx.qh.response.QrCodeResponse;
import com.yp.loading.base.BaseDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

/**
 * @ClassName: TokenEmptyDialog
 * @Description: 成绩相关
 * @Author: ljf89 (刘江飞)
 * @Date: 2021/1/15-- 18:10
 * @Email: 642371742@qq.com
 */
public class PlaybillDialog extends BaseDialog {
    private RoundedImageView riv_user_photo;
    private TextView tv_username;
    private ImageView iv_qr_code;
    private TextView tv_cancel;
    private TextView tv_save;
    private FrameLayout fl_bill;

    @Override
    public boolean isCancelable() {
        return false;
    }

    @Override
    protected boolean isCancelOutside() {
        return false;
    }

    @Override
    protected int setLayoutId() {
        return R.layout.dialog_playbill;
    }

    @Override
    protected void initView() {
        super.initView();
        riv_user_photo = mRootView.findViewById(R.id.riv_user_photo);
        tv_username = mRootView.findViewById(R.id.tv_username);
        iv_qr_code = mRootView.findViewById(R.id.iv_qr_code);
        tv_cancel = mRootView.findViewById(R.id.tv_cancel);
        tv_save = mRootView.findViewById(R.id.tv_save);
        fl_bill = mRootView.findViewById(R.id.fl_bill);
    }

    @Override
    protected void initData() {
        super.initData();
        loadBill();
    }

    private void loadBill() {
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL_1)
                .appendUrl("user/qr")
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        String url = getQrCodeUrl(json);
                        loadUserInfo(url);
                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        super.onError(e);
                        Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void loadUserInfo(String url) {
        new Thread(() -> Glide.with(mActivity)
                .asBitmap()
                .load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        mActivity.runOnUiThread(() -> iv_qr_code.setImageBitmap(resource));
                    }
                })).start();
        String user_photo = (String) SPUtils.get(mActivity, ConstantsConfig.USER_PHOTO, "");
        new Thread(() -> Glide.with(mActivity)
                .asBitmap()
                .load(user_photo)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        mActivity.runOnUiThread(() -> riv_user_photo.setImageBitmap(resource));
                    }
                })).start();
        String username = (String) SPUtils.get(mActivity, ConstantsConfig.USER_NAME, "");
        if (username != null) {
            tv_username.setText(username);
        }
    }

    private String getQrCodeUrl(String json) {
        Gson gson = new Gson().newBuilder().create();
        if (json == null || json.isEmpty()) {
            return null;
        }
        BaseResponse<QrCodeResponse> response = gson.fromJson(json, new TypeToken<BaseResponse<QrCodeResponse>>() {
        }.getType());
        if (response == null) {
            return null;
        }
        QrCodeResponse qrCodeResponse = gson.fromJson(gson.toJson(response.data), new TypeToken<QrCodeResponse>() {
        }.getType());
        if (qrCodeResponse.url_qr == null) {
            return null;
        }
        return qrCodeResponse.url_qr;
    }

    @Override
    protected void setListener() {
        super.setListener();
        tv_cancel.setOnClickListener(this);
        tv_save.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_cancel) {
            dismiss();
        }
        if (v.getId() == R.id.tv_save) {
            new Thread(() -> {
                fl_bill.buildDrawingCache();
                Bitmap bitmap = fl_bill.getDrawingCache();
                String fileName = getFileName();
                saveBitmap(mActivity, bitmap, fileName);
                mActivity.runOnUiThread(() -> dismiss());
            }).start();

        }
    }

    private String getFileName() {
        Calendar cal = Calendar.getInstance();

        //当前年
        int year = cal.get(Calendar.YEAR);
        //当前月
        int month = (cal.get(Calendar.MONTH)) + 1;
        //当前月的第几天：即当前日
        int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
        //当前时：HOUR_OF_DAY-24小时制；HOUR-12小时制
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        //当前分
        int minute = cal.get(Calendar.MINUTE);
        //当前秒
        int second = cal.get(Calendar.SECOND);
        String time = year + ""
                + month + ""
                + day_of_month + ""
                + hour + ""
                + minute + ""
                + second;

        return time + ".jpg";
    }

    /*
     * 保存文件，文件名为当前日期
     */
    public void saveBitmap(Context context, Bitmap bitmap, String bitName) {
        if (bitmap == null) {
            mActivity.runOnUiThread(() -> Toast.makeText(mActivity, "图片资源为空", Toast.LENGTH_SHORT).show());
            return;
        }
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            Log.v("qwe", "002");
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        mActivity.runOnUiThread(() -> Toast.makeText(mActivity, "保存图片成功", Toast.LENGTH_SHORT).show());
    }
}
